package com.elite.groovy.callback
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.elite.groovy.util.EliteBean;
import com.elite.groovy.util.Util
import net.sf.json.JSONObject

/**
 * @author 续保外呼数据接收
 */
public class RenewalDataReceive implements ServiceBackInvoke {
    private static final Log logger = LogFactory.getLog(RenewalDataReceive.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        request.setCharacterEncoding("UTF-8"); // 防止中文乱码
        response.setCharacterEncoding("UTF-8");
        def code = "";
        def msg = "";
        def CUST_STATUS = "1";
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //接收JSON入参
        String requestBody = Util.getRequestBody(request, "utf-8");

        logger.info("RenewalDataReceive 请求报文: ${requestBody}");
        //定义返回JSON
        JSONObject jsonALL1 = new JSONObject();
        try {
            JSONObject requestBodyJsonObject = JSONObject.fromObject(requestBody);
            String POLICYNO = requestBodyJsonObject.get("POLICYNO"); // 保单号
            if(POLICYNO == "null"){
                POLICYNO = '';
            }
            String RISKCODE = requestBodyJsonObject.get("RISKCODE"); // 险种
            if(RISKCODE == "null"){
                RISKCODE = '';
            }
            String RISKNAME = requestBodyJsonObject.get("RISKNAME"); // 产品名称
            if(RISKNAME == "null"){
                RISKNAME = '';
            }

            String LICENSENO = requestBodyJsonObject.get("LICENSENO"); // 车牌号
            if(LICENSENO == "null"){
                LICENSENO = '';
            }
            String FRAMENO = requestBodyJsonObject.get("FRAMENO"); // 车架号
            if(FRAMENO == "null"){
                FRAMENO = '';
            }
            String APPLICODE = requestBodyJsonObject.get("APPLICODE"); // 投保人
            String APPLINAME = requestBodyJsonObject.get("APPLINAME"); // 投保人名称
            String INSUREDCODE = requestBodyJsonObject.get("INSUREDCODE"); // 被保险人
            String INSUREDNAME = requestBodyJsonObject.get("INSUREDNAME"); // 被保险人名称
            String APPLI_PHONE = requestBodyJsonObject.get("APPLI_PHONE"); // 投保人联系方式
            String INSURED_PHONE = requestBodyJsonObject.get("INSURED_PHONE"); // 被保险人联系方式
            Double SUMPREMIUM = null;

            if(null!=requestBodyJsonObject.get("SUMPREMIUM") && !requestBodyJsonObject.get("SUMPREMIUM").equals("")){
                SUMPREMIUM = requestBodyJsonObject.get("SUMPREMIUM");
            }; // 含税保费

            String BUSINESSNATURE = requestBodyJsonObject.get("BUSINESSNATURE"); // 业务来源
            String STARTDATE = requestBodyJsonObject.get("STARTDATE"); // 起保日期
            String ENDDATE = requestBodyJsonObject.get("ENDDATE"); // 终保日期
            String COMCODE = requestBodyJsonObject.get("COMCODE"); // 归属机构
            String GROUPCODE = requestBodyJsonObject.get("GROUPCODE"); // 归属团队
            String HANDLERCODE = requestBodyJsonObject.get("HANDLERCODE"); // 业务员
            String RECEIPOR = requestBodyJsonObject.get("RECEIPOR"); // 认领人员
            String RENEWALFLAG = requestBodyJsonObject.get("RENEWALFLAG"); // 续保状态
            String GROUPNO1 = requestBodyJsonObject.get("GROUPNO1"); // 团单编号
            String AGENTCODE = requestBodyJsonObject.get("AGENTCODE"); // 代理人
            String ACCEPT_YEARS = requestBodyJsonObject.get("ACCEPT_YEARS"); // 承保年限
            String MAINPOLICYNO = requestBodyJsonObject.get("MAINPOLICYNO"); // 关联保单号
            String DEALER_CODE = requestBodyJsonObject.get("DEALER_CODE"); // 处理人代码
            String CREATE_TIME = requestBodyJsonObject.get("CREATE_TIME"); // 创建日期
            String CREATE_BY = requestBodyJsonObject.get("CREATE_BY"); // 创建人a
            String UPDATE_TIME = requestBodyJsonObject.get("UPDATE_TIME"); // 更新日期
            String UPDATE_BY = requestBodyJsonObject.get("UPDATE_BY"); // 更新人
            Double SUMEXPIRATION = null;
            if(null!=requestBodyJsonObject.get("SUMEXPIRATION") && !requestBodyJsonObject.get("SUMEXPIRATION").equals("")){
                SUMEXPIRATION = requestBodyJsonObject.get("SUMEXPIRATION");
            };
            //Double SUMEXPIRATION = Double.valueOf(requestBodyJsonObject.getString("SUMEXPIRATION")); // 满期保费
            String ISTWENTYFLAG = requestBodyJsonObject.get("ISTWENTYFLAG"); // 交强险新旧标识：0-旧，1-新
            String POSTCODE = requestBodyJsonObject.get("POSTCODE"); // 邮政编码
            String QUOTATIONTIMES = requestBodyJsonObject.get("QUOTATIONTIMES"); // 报价次数
            String RISKCLASS = requestBodyJsonObject.get("RISKCLASS"); // 险类
            String ISSUEORG = requestBodyJsonObject.get("ISSUEORG"); // 出单机构
            String ISSUESTAFF = requestBodyJsonObject.get("ISSUESTAFF"); // 出单员
            String AGENTAGREEMENTNO = requestBodyJsonObject.get("AGENTAGREEMENTNO"); // 代理人协议号
            String CHANNELFLAG = requestBodyJsonObject.get("CHANNELFLAG"); // OLS-网销出单，MID-中台出单
            String ORDERNUMBER = requestBodyJsonObject.get("ORDERNUMBER"); // 订单号
            String ISCAR = requestBodyJsonObject.get("ISCAR"); // 是否车险1车险，0非车
            String APPLIIDENGTIFYNO = requestBodyJsonObject.get("APPLIIDENGTIFYNO"); // 投保人证件号码
            String CARATTACHNATURE = requestBodyJsonObject.get("CARATTACHNATURE"); // 车辆所属性质
            String USEKINDCODE = requestBodyJsonObject.get("USEKINDCODE"); // 使用性质代码
            String CARTYPE = requestBodyJsonObject.get("CARTYPE"); // 车辆种类
            String RENEWALEXPIRETIME = requestBodyJsonObject.get("RENEWALEXPIRETIME"); // 续保失效时间
            String GOODSID = requestBodyJsonObject.get("GOODSID"); // 商品ID
            String GOODSNAME = requestBodyJsonObject.get("GOODSNAME"); // 商品名称
            String PLANNAME = requestBodyJsonObject.get("PLANNAME"); // 计划名称
            String BUSINESSTYPE = requestBodyJsonObject.get("BUSINESSTYPE"); // 业务分类
            String AGENTCOMPANY = requestBodyJsonObject.get("AGENTCOMPANY"); // 代理公司
            String HANDLER1CODE = requestBodyJsonObject.get("HANDLER1CODE"); // 业务员
            String OBJECTIVETYPE = requestBodyJsonObject.get("OBJECTIVETYPE"); // 任务类型
			String APP_AUTHRESULT = requestBodyJsonObject.get("APP_AUTHRESULT"); // 客户三要素

            if (POLICYNO.isEmpty() || RISKCODE.isEmpty() || RISKNAME.isEmpty()){ //‘保单号’或‘险种’或‘产品名称’为空
                CUST_STATUS = "98";
            }

            if (LICENSENO.isEmpty() && FRAMENO.isEmpty()){ //‘车牌号’和‘车架号’为空
                CUST_STATUS = "98";
            }

            logger.info("CUST_STATUS:" + CUST_STATUS);

            def selectSql=""" select customer_guid as "customerGuid", case when '${RISKCODE}' = 'DFA' then lastcommercialpolicyno else lastaccidentpolicyno end as "MAINPOLICYNO" from customer where FRAMENO=? and rownum =? and datatype = 'xb' """;
            def v_row=1;
            def selectSqlResult=jt.queryForList(selectSql,FRAMENO,v_row);
            def v_customerGuid;
            def v_relation_id;
            v_relation_id=UUID.randomUUID().toString();

            if(selectSqlResult !=''&& selectSqlResult.size()>0) {
                def map_sub=selectSqlResult[0];
                v_customerGuid = map_sub.get("customerGuid");
                MAINPOLICYNO = map_sub.get("MAINPOLICYNO");

                String updatesql = "update CUSTOMER set lastaccidentpolicyno=decode('$RISKCODE','1101','$POLICYNO',lastaccidentpolicyno),lastcommercialpolicyno=decode('$RISKCODE','1101',lastcommercialpolicyno,'$POLICYNO'), qq='$APP_AUTHRESULT' where customer_guid='$v_customerGuid'";

                eliteBean.update(updatesql, "dataSource");
            }else{
                v_customerGuid=UUID.randomUUID().toString();
                def lastaccidentpolicyno = "";
                def lastcommercialpolicyno = "";
                if(RISKCODE=='1101'){
                    lastaccidentpolicyno = POLICYNO;
                }else{
                    lastcommercialpolicyno = POLICYNO;
                }
                String insertCUST = """insert into CUSTOMER(customer_guid, LICENSENO,FRAMENO, lastaccidentpolicyno,lastcommercialpolicyno, BUSINESSNATURE, CUSTOMER_ID, CUSTOMERNAME, CUSTOMERTYPE2_ID, MOBILE, TEL_1, CREATEDDATE, CREATEDBY, stringfield20, datatype,qq) values ('${v_customerGuid}','${LICENSENO}','${FRAMENO}','${lastaccidentpolicyno}','${lastcommercialpolicyno}','${BUSINESSNATURE}','${APPLIIDENGTIFYNO}','${INSUREDNAME}','000002','${INSURED_PHONE}','${APPLI_PHONE}',sysdate,'SYSTEM','${LICENSENO}','xb','$APP_AUTHRESULT') """;
                eliteBean.update(insertCUST, "dataSource");
            }

                String insertSQL = """insert into XB_CUST_CASE(RELATION_ID, ELITETASK_GUID, CUSTOMER_GUID, CUST_STATUS, CREATE_USER, CREATE_DATE, CUSTLIST_XXX, POLICYNO, RISKCODE, RISKNAME, LICENSENO, FRAMENO, APPLICODE, APPLINAME, INSUREDCODE, INSUREDNAME, APPLI_PHONE, INSURED_PHONE, SUMPREMIUM, BUSINESSNATURE, STARTDATE, ENDDATE, COMCODE, GROUPCODE, HANDLERCODE, RECEIPOR, RENEWALFLAG, GROUPNO1, AGENTCODE, ACCEPT_YEARS, MAINPOLICYNO, DEALER_CODE, CREATE_TIME, CREATE_BY, UPDATE_TIME, UPDATE_BY, SUMEXPIRATION, ISTWENTYFLAG, POSTCODE, QUOTATIONTIMES, RISKCLASS, ISSUEORG, ISSUESTAFF, AGENTAGREEMENTNO, CHANNELFLAG, ORDERNUMBER, ISCAR, APPLIIDENGTIFYNO, CARATTACHNATURE, USEKINDCODE, CARTYPE, RENEWALEXPIRETIME, GOODSID, GOODSNAME, PLANNAME, BUSINESSTYPE, AGENTCOMPANY, HANDLER1CODE, OBJECTIVETYPE ) values ('${v_relation_id}','XBTS'||sys_guid(),'${v_customerGuid}','${CUST_STATUS}','SYSTEM',sysdate,'XB'||to_char(sysdate,'yyyymmdd'),'${POLICYNO}','${RISKCODE}','${RISKNAME}','${LICENSENO}','${FRAMENO}','${APPLICODE}','${APPLINAME}','${INSUREDCODE}','${INSUREDNAME}','${APPLI_PHONE}','${INSURED_PHONE}',${SUMPREMIUM},'${BUSINESSNATURE}','${STARTDATE}','${ENDDATE}','${COMCODE}','${GROUPCODE}','${HANDLERCODE}','${RECEIPOR}','${RENEWALFLAG}','${GROUPNO1}','${AGENTCODE}','${ACCEPT_YEARS}','${MAINPOLICYNO}','${DEALER_CODE}','${CREATE_TIME}','${CREATE_BY}','${UPDATE_TIME}','${UPDATE_BY}',${SUMEXPIRATION},'${ISTWENTYFLAG}','${POSTCODE}','${QUOTATIONTIMES}','${RISKCLASS}','${ISSUEORG}','${ISSUESTAFF}','${AGENTAGREEMENTNO}','${CHANNELFLAG}','${ORDERNUMBER}','${ISCAR}','${APPLIIDENGTIFYNO}','${CARATTACHNATURE}','${USEKINDCODE}','${CARTYPE}','${RENEWALEXPIRETIME}','${GOODSID}','${GOODSNAME}','${PLANNAME}','${BUSINESSTYPE}','${AGENTCOMPANY}','${HANDLER1CODE}','${OBJECTIVETYPE}')""";

            eliteBean.update(insertSQL, "dataSource");

            Map data = new HashMap();
            data.put("relation_id", v_relation_id);
            data.put("cust_id",v_customerGuid);
            List datalist = new ArrayList();
            datalist.add(data);

            code = "200";
            msg = "接收成功";
            jsonALL1.put("code", code);
            jsonALL1.put("msg", msg);
            jsonALL1.put("data", datalist);
        } catch (Exception e) {
            logger.error("RenewalDataReceive doCallBack 发生异常!  " + Util.getERRO(e));
            code = "0000";
            msg = "调用失败";
            jsonALL1.put("code", code);
            jsonALL1.put("msg", msg);
            logger.debug("异常----------------:" + e);
        }
        return jsonALL1;
    }
}